<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>localStorage</title>
  </head>
  <body>
    <h2>localStorage</h2>
    <button onclick="saveData()">点我保存一个数据</button>
    <button onclick="readData()">点我读取一个缓存</button>
    <button onclick="deleteData()">点我删除一个数据</button>
    <button onclick="deleteAllData()">点我清空数据</button>
    <script>
      let p = { name: "张三", age: 19 };
      console.log(p.toString());
      function saveData() {
        //  注意key和value都是字符串
        //  只要value不是string类型，就会自动调用toString转换为字符串
        localStorage.setItem("key", "value");
        localStorage.setItem("person", p);
        localStorage.setItem("person2", JSON.stringify(p));
        // JSON.stringfy ==》 JS————JSON字符串
      }
      function readData() {
        console.log(localStorage.getItem("key"));
        console.log(localStorage.getItem("person"));

        const result = localStorage.getItem("person2");
        console.log(JSON.parse(result));
        // JSON.parse  ==》 JSON字符串————JS对象
      }
      function deleteData() {
        localStorage.removeItem("key");
        localStorage.removeItem("person2");
      }
      function deleteAllData() {
        localStorage.clear();
      }
    </script>
  </body>
</html>
